import { map, max } from 'lodash';
import type { Model } from '@antv/x6';

export interface INode {
  code: string;
  name: string;
  id?: string;
  label?: string;
  children?: INode[];
}

export interface HierarchyResult {
  id: number;
  x: number;
  y: number;
  children: HierarchyResult[];
  data: INode;
}

export const initNode = {
  code: 'Single Node',
  name: 'New Node',
};

export const formatData = (data: any, parentIndex?: string): any => {
  const prefix = parentIndex ? `${parentIndex}-` : '';
  return map(data, (item: INode, i: number) => ({
    ...item,
    id: `${prefix}${i}`,
    children: formatData(item.children, `${prefix}${i}`),
  }));
};

export const generateModal = (result: HierarchyResult) => {
  const model: Model.FromJSONData = { nodes: [], edges: [] };
  const traverse = (data: HierarchyResult) => {
    // console.log(data);
    if (data) {
      model.nodes?.push({
        id: `${data.id}`,
        x: data.x,
        y: data.y,
        shape: 'rect',
        width: data.data?.label?.length
          ? max([data.data.label.length * 16, 100])
          : 100,
        height: 40,
        label: data.data.label,
        data: data.data,
        attrs: {
          body: {
            fill: '#fff',
            stroke: '#000',
          },
          label: {
            textWrap: {
              ellipsis: true,
            },
          },
        },
      });
    }

    if (data.children.length) {
      data.children.forEach((item: HierarchyResult) => {
        model.edges?.push({
          source: `${data.id}`,
          target: `${item.id}`,
          attrs: {
            line: {
              stroke: '#000',
              strokeWidth: 1,
            },
          },
        });
        traverse(item);
      });
    }
  };
  traverse(result);
  return model;
};
